package me.skyun.androidarch.connect;

import android.os.Handler;
import android.os.Looper;

import java.io.Closeable;
import java.io.IOException;

import me.skyun.androidarch.common.Utils;
import me.skyun.androidarch.connect.Client;
import me.skyun.androidarch.connect.Connection;

/**
 * Created by skyun on 17/8/21.
 */

public abstract class ConnClient<C extends Closeable> extends Thread implements Client {

    private Connection.Callback mCallback = new Connection.DefaultCallback();

    public ConnClient(Connection.Callback callback) {
        mCallback = callback;
    }

    protected abstract C connect() throws IOException;

    protected abstract String getRemoteName();

    public void run() {
        C socket;
        try {
            socket = connect();
        } catch (IOException e) {
            Utils.logMsg("Failed to startRun: " + e.getMessage());
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    mCallback.onStateChanged(null, Connection.State.Disconnected);
                }
            });
            return;
        }
        Utils.logMsg("Connect success: " + getRemoteName());

        Connection connection = new Connection(socket, mCallback);
        connection.start();
    }

    @Override
    public void startRun() {
        start();
        mCallback.onStateChanged(null, Connection.State.Connecting);
    }
}
